package com.ai.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final String SECRET_KEY = "ysw@ai.com";

    //private static final long REFRESH_TOKEN_EXPIRATION_TIME = 604800000; // 7 days
    private static final long REFRESH_TOKEN_EXPIRATION_TIME = 30 * 1000; // 30s

    /**
     * 获取Token
     * @param phone
     * @param userName
     * @param expirationTime
     * @return
     */
    public static String generateToken(String phone,String userName, long expirationTime) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("phone", phone);
        claims.put("userName", userName);

        return Jwts.builder()
                .setClaims(claims)
                //.setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    /**
     * 获取Token
     * @param username
     * @return
     */
    public static String generateToken(String phone,String username) {
        return generateToken(phone,username,REFRESH_TOKEN_EXPIRATION_TIME);
    }

    /**
     * 验证Token
     * @param token
     * @return
     */
    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 刷新token
     * @param token
     * @return
     */
    public static String refreshToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        String refreshedToken = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
        return refreshedToken;
    }

    /**
     * 获取用户电话号码
     * @param token
     * @return
     */
    public static String getPhoneFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
        return claims.get("phone", String.class);
    }
    /**
     * 获取用户名称
     * @param token
     * @return
     */
    public static String geUserNameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
        return claims.get("userName", String.class);
    }
}
